'use strict'

/**
 * @method prependChild
 * @description dom元素里面的前面 插入元素
 * @param {HTMLElement} [o] 待插入元素
 * @param {HTMLElement} [s]  父元素
 */
export function prependChild (o: HTMLElement, s: HTMLElement) {
  if (s.hasChildNodes()) {
    s.insertBefore(o, s.firstChild);
  } else {
    s.appendChild(o);
  }
}

/**
 * @method pullDownRefresh
 * @description 给元素添加下拉刷新事件
 * @param {HTMLElement} [refreshContainer] 可添加下拉事件的容器
 * @param {HTMLElement} [outerScroller] 外部滚动容器（也可以是下拉事件容器本身）
 * @param {function} [refreshFn] 下拉结束之后执行刷新的函数
 */
export function pullDownRefresh (refreshContainer: HTMLElement, outerScroller: HTMLElement, refreshFn?: Function) {
  if (!(refreshContainer instanceof Element)) {
    return '不是Dom元素哈哈哈';
  }
  const idName = 'pullDownRefreshTopTips', triggerDis = 120;
  let touchStart = 0, touchDis = 0;
  refreshContainer.addEventListener('touchstart', function (event: TouchEvent) {
    const touch = event.targetTouches[0];
    // 把元素放在手指所在的位置
    // 触屏开始的位置
    touchStart = touch.pageY;
  }, false);
  refreshContainer.addEventListener('touchmove', function (event: TouchEvent) {
    const touch = event.targetTouches[0];
    // 手指划过的距离
    touchDis = touch.pageY - touchStart;
    // 移动的距离等于它的起始位置加上鼠标移动的距离
    if (touchDis > triggerDis) {
      if (!document.getElementById(idName)) {
        const tag = document.createElement('div');
        tag.setAttribute('id', idName);
        tag.style.cssText = 'line-height: 60px; text-align: center; font-size: 16px; color: #999999;';
        tag.innerText = '即将刷新...';
        prependChild(tag, outerScroller);
      }
    }
  }, false);
  refreshContainer.addEventListener('touchend', function () {
    // 容器下滑到达的位置
    if (touchDis > triggerDis && outerScroller.scrollTop === 0) {
      refreshFn();
    }
    setTimeout(() => {
      const refreshTips = document.getElementById(idName);
      refreshTips && outerScroller.removeChild(refreshTips);
    }, 500);
    touchDis = 0;
    touchStart = 0;
  }, false);
}

/**
 * @method openWindow
 * @description 打开浏览器新窗口
 * @author hjp
 * @date 2021-07-02 15:07:03
 * @param {string} [url] 打开的窗口URL地址
 * @param {string} [target='_blank'] 是否新开页面
 */
export function openWindow (url: string, target = '_blank') {
    const $link = document.createElement('a');
    $link.href = url;
    $link.setAttribute('target', target);
    document.body.appendChild($link);
    $link.click();
    document.body.removeChild($link);
  }


/**
 * @method closeWindow
 * @description 关闭浏览器窗口
 * @author hjp
 * @date 2021-07-02 15:07:03
 */
export function closeWindow () {
  if (navigator.userAgent.indexOf('Firefox') !== -1 || navigator.userAgent.indexOf('Chrome') !== -1) {
    window.location.href = 'about:blank';
    window.close();
  } else {
    window.opener = null;
    window.open('', '_self');
    window.close();
  }
}

/**
 * @method openWindowCompatibility
 * @description 新开窗口 兼容iframe嵌套新开河safari
 * @param {string} [url] 打开的窗口URL地址
 * @date 2022-03-15 15:07:03
 */
export function openWindowCompatibility (url: string) {
  if (window.self !== window.top) {
    window.open(url, 'iframe');
  } else {
    window.open(url, 'blank');
  }
}

/**
 * @method closeWindowCompatibility
 * @description 关闭新开窗口 兼容iframe嵌套新开河safari
 * @date 2022-03-15 15:07:03
 */
export function closeWindowCompatibility () {
  if (window.self !== window.top) {
    window.history.back();
  } else {
    window.open('about:blank', '_top').close();
  }
}


/**
 * @method loadScript
 * @description  动态加载js
 * @author yanghaiyang
 * @date 2020-03-25
 * @param {String} url 要加载的script文件路径
 * @param {String} [id] 如果传入id 会避免有需要的场景下面重复添加script标签
 * @returns {Promise}
 */
export function loadScript(url: string, id?: string, attrs = {}) {
  return new Promise((resolve) => {
    let script: HTMLScriptElement = document.createElement('script')
    script.type = 'text/javascript'
    if (id) {
      const existScript = document.getElementById(id);
      if (existScript) {
        script = null;
        resolve('ok');
        return;
      } else {
        script.id = id;
      }
    }
    for (const attrsKey in attrs) {
      const i = attrs[attrsKey];
      script.setAttribute(attrsKey, i);
    }
    // @ts-ignore
    if (script.readyState) {
      //IE
       // @ts-ignore
      script.onreadystatechange = function() {
         // @ts-ignore
        if (script.readyState == 'loaded' || script.readyState == 'complete') {
           // @ts-ignore
          script.onreadystatechange = null
          resolve('ok')
        }
      }
    } else {
      //Others
      script.onload = function() {
        resolve('ok')
      }
    }
    script.src = url
    document.getElementsByTagName('head')[0].appendChild(script)
  })
}

export interface OsType {
  isChrome: boolean;
  isTablet: boolean;
  isIPhone: boolean;
  isAndroid: boolean;
  isPc: boolean;
  isWechat: boolean;
  isDingTalk: boolean;
  isYXGS: boolean;
}

/**
 * @method getOs
 * @description 获取系统信息
 * @author yanghaiyang
 * @date 2022-03-25
 * @returns {OsType}
 */
export function getOs (): OsType {
  const ua = navigator.userAgent,
    isWindowsPhone = /(?:Windows Phone)/.test(ua),
    isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
    isAndroid = /(?:Android)/.test(ua),
    isFireFox = /(?:Firefox)/.test(ua),
    isChrome = /(?:Chrome|CriOS)/.test(ua),
    isTablet = /.*uxin_android.*\/pad\//g.test(ua) || /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)),
    isIPhone = /(?:iPhone)/.test(ua) && !isTablet,
    isPc = !isIPhone && !isAndroid && !isSymbian,
    // @ts-ignore
    isWechat = ua.toLowerCase().includes('micromessenger'),
    isDingTalk = ua.toLowerCase().includes('dingtalk'),
    isYXGS = ua.indexOf('mobile/parent/yxgs') > -1;
  return {
    isChrome,
    // 平板
    isTablet,
    // 苹果手机
    isIPhone,
    // 安卓手机
    isAndroid,
    // PC端
    isPc,
    // 微信
    isWechat,
    // 钉钉
    isDingTalk,
    // 优学高手APP
    isYXGS
  };
}

/**
 * @method isMobile
 * @description  判断是否为移动端
 * @author yanghaiyang
 * @date 2020-07-20 14:20
 * @returns {Boolean}
 */
export function isMobile () {
  const os = getOs();
  return (os.isAndroid || os.isIPhone) && !os.isTablet;
}


/**
 * 可视化大屏的适配
 * @param designWidth
 * @param designHeight
 * @param renderDom
 */
export function keepFit (designWidth, designHeight, renderDom) {
  const clientHeight = document.documentElement.clientHeight;
  const clientWidth = document.documentElement.clientWidth;
  let scale = 1;
  if (clientWidth / clientHeight < designWidth / designHeight) {
    scale = (clientWidth / designWidth)
    document.querySelector(renderDom).style.height = `${clientHeight / scale}px`;
  } else {
    scale = (clientHeight / designHeight)
    document.querySelector(renderDom).style.width = `${clientWidth / scale}px`;
  }
  document.querySelector(renderDom).style.transform = `scale(${scale})`;
}

